﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RavenAcessLayer
{
    public class DomainObject
    {
        //All documents get an Id created by Raven when stored
        public string Id { get; set; }
        public DateTime CreateDate { get; set; }
        public DateTime MofiyDate { get; set; }

        //Reload Object from database
        public void Reload()
        {
            DataContext.Db.Session.Advanced.Refresh(this);
        }

        //Persistance Methods
        public DataObjectOperationResult Save()
        {
            DataContext.Db.Session.Store(this);
            return this.Commit();
        }

        public DataObjectOperationResult Delete()
        {
            DataContext.Db.Session.Delete(this);
            return this.Commit();
        }

        private DataObjectOperationResult Commit()
        {
            var result = new DataObjectOperationResult();
            try
            {
                DataContext.Db.Session.Store(this);
                DataContext.Db.Session.SaveChanges();

                result.Success = true;
                result.Message = "Database Update Completed Successfully";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }

            return result;
        }

        #region Save With Validation

        public DataObjectOperationResult ValidateAndSave()
        {
            var result = AttributeValidator.ValidateDataObject(this);
            if (result.Success == true)
            {
                DataContext.Db.Session.Store(this);
                return this.Commit();
            }
            return result;
        }

        #endregion
    }
}
